<template>
    <div class="merchant-container">
        <!-- 头部 -->
        <div class="header">
            <h2 class="title">商户信息管理</h2>
            <el-button
                    v-if="!isEditing"
                    type="primary"
                    icon="el-icon-edit"
                    @click="startEditing"
            >编辑信息</el-button>
        </div>

        <!-- 信息展示 -->
        <div v-if="!isEditing" class="info-panel">
            <!-- 基础信息 -->
            <div class="section">
                <h3 class="section-title">基础信息</h3>
                <div class="info-grid">
                    <div class="info-item">
                        <label>商户名称：</label>
                        <span>{{ merchantInfo.name}}</span>
                    </div>
                    <div class="info-item">
                        <label>联系人姓名：</label>
                        <span>{{ merchantInfo.contactName}}</span>
                    </div>
                    <div class="info-item">
                        <label>联系电话：</label>
                        <span>{{ merchantInfo.contactPhone }}</span>
                    </div>
                </div>
            </div>

            <!-- 地址信息 -->
            <div class="section">
                <h3 class="section-title">经营地址</h3>
                <div class="address-box">
                    <el-icon class="location-icon"><i class="el-icon-location-outline"></i></el-icon>
                    <div class="address-content">
                        <div class="address-line" v-if="merchantInfo.address">
                            <span class="address-tag">省市区</span>
                            <span class="address-text">{{ formatProvinceCityDistrict(merchantInfo.address) }}</span>
                        </div>
                        <div class="address-line" v-if="merchantInfo.addressDetail">
                            <span class="address-tag">详细地址</span>
                            <span class="address-text">{{ merchantInfo.addressDetail }}</span>
                        </div>
                        <div v-if="!merchantInfo.address && !merchantInfo.addressDetail" class="no-address">
                            暂无地址信息
                        </div>
                    </div>
                </div>
            </div>

            <!-- 证照信息部分 -->
            <div class="section">
                <h3 class="section-title">资质证照</h3>
                <div class="license-grid">
                    <div class="logo-box">
                        <div class="preview-title">商户LOGO</div>
                        <div class="image-container logo-wrapper">
                            <el-image
                                :src="merchantInfo.logo"
                                fit="cover"
                                class="preview-image logo-image"
                                :preview-src-list="[merchantInfo.logo]"
                            />
                            <div class="image-hover-text">点击查看大图</div>
                        </div>
                    </div>
                    <div class="license-box">
                        <div class="preview-title">营业执照</div>
                        <div class="image-container license-wrapper">
                            <el-image
                                :src="merchantInfo.license"
                                fit="contain"
                                class="preview-image license-image"
                                :preview-src-list="[merchantInfo.license]"
                            />
                            <div class="image-hover-text">点击查看大图</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

<!--        编辑弹框-->
        <el-dialog
            title="编辑商户信息"
            :visible.sync="isEditing"
            width="800px"
            @close="cancelEditing"
        >
            <el-form
                ref="editForm"
                :model="merchantInfo"
                label-width="120px"
                :rules="formRules"
            >
                <!-- 基础信息 -->
                <el-form-item label="商户名称：" prop="name">
                    <el-input
                        v-model="merchantInfo.name"
                        placeholder="请输入商户名称"
                        clearable
                    />
                </el-form-item>

                <el-form-item label="联系人姓名：" prop="contactName">
                    <el-input
                        v-model="merchantInfo.contactName"
                        placeholder="请输入联系人姓名"
                        clearable
                    />
                </el-form-item>

                <el-form-item label="联系电话：" prop="contactPhone">
                    <el-input
                        v-model="merchantInfo.contactPhone"
                        placeholder="请输入联系电话"
                        clearable
                    />
                </el-form-item>

                <!-- 地址信息 -->
                <el-form-item label="所在地区：" prop="address">
                    <el-cascader
                        v-model="merchantInfo.address"
                        :options="regionData"
                        :props="{
                                  expandTrigger: 'hover',
                                  value: 'value',
                                  label: 'label',
                                  children: 'children'
                                 }"
                        clearable
                        filterable
                        placeholder="请选择省/市/区"
                        style="width: 100%"
                    />

                </el-form-item>

                <el-form-item label="详细地址：" prop="addressDetail">
                    <el-input
                        v-model="merchantInfo.addressDetail"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入详细地址"
                    />
                </el-form-item>

                <!-- 图片上传 -->
                <el-form-item label="商户LOGO：">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleLogoSuccess"
                    >
                        <img
                            v-if="merchantInfo.logo"
                            :src="merchantInfo.logo"
                            class="avatar"
                        >
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                </el-form-item>

                <el-form-item label="营业执照：">
                    <el-upload
                        class="license-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleLicenseSuccess"
                    >
                        <img
                            v-if="merchantInfo.license"
                            :src="merchantInfo.license"
                            class="license"
                        >
                        <div v-else class="uploader-placeholder">
                            <i class="el-icon-plus" />
                            <span>上传营业执照</span>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEditing">取 消</el-button>
                <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="submitting"
                >确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import {regionData,  codeToText} from 'element-china-area-data'
export default {
    data() {
        // 手机号验证规则
        const validatePhone = (rule, value, callback) => {
            if (!/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号码'))
            } else {
                callback()
            }
        }
        return {
            isEditing: false,
            merchantInfo: {},//商户对象

            regionData: regionData,
            CodeToText: codeToText, // 将 CodeToText 存入 data 中

            submitting: false,
            originalInfo: {}, // 存储原始数据用于取消时恢复
            formRules: {
                name: [
                    { required: true, message: '请输入商户名称', trigger: 'blur' },
                    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
                ],
                contactName: [
                    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
                ],
                contactPhone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { validator: validatePhone, trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请选择所在地区', trigger: 'change' }
                ],
                addressDetail: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ]
            },
            uploadUrl: process.env.VUE_APP_BASE_API + '/upload' // 根据实际接口调整
        }
    },
    methods: {
        // 格式化省市区地址
        formatProvinceCityDistrict(codes) {
            if (!codes) return ''

            const codeArray = typeof codes === 'string' ? codes.split(',') : codes
            if (codeArray.length < 3) return codes

            const [provinceCode, cityCode, districtCode] = codeArray
            const province = this.CodeToText[provinceCode] || ''
            const city = this.CodeToText[cityCode] || ''
            const district = this.CodeToText[districtCode] || ''

            // 格式化为"XX省 XX市 XX区"
            return `${province} ${city} ${district}`.trim()
        },
        //查询商户信息
        searchMerchantInfo() {
            let user = JSON.parse(sessionStorage.getItem('user'))
            this.$axios.post(`login/selectIdMerchants/${user.id}`).then(r =>{
                console.log(222,r.data)
                const data = r.data.merchants;
                // 转换地址数据为数组格式
                this.merchantInfo = {
                    ...data,
                    address: data.address ? data.address.split(',') : []
                };
                this.isEditing = false
            })
        },
        // 点击编辑时
        startEditing() {
            // 深拷贝时保持数组格式
            this.originalInfo = JSON.parse(JSON.stringify({
                ...this.merchantInfo,
                address: [...this.merchantInfo.address]
            }));
            this.isEditing = true
        },

        // 取消编辑
        cancelEditing() {
            this.merchantInfo = JSON.parse(JSON.stringify(this.originalInfo))
            this.isEditing = false
        },

        // 提交表单
        submitForm() {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.submitting = true
                    // 转换地址数据为字符串
                    const submitData = {
                        ...this.merchantInfo,
                        address: this.merchantInfo.address.join(',')
                    }

                    this.$axios.put('/merchant/MerchantsUpdate', submitData)
                        .then(response => {
                            if (response.data == 'yes'){
                                this.$message.success('修改成功')
                                this.searchMerchantInfo()
                                this.isEditing = false
                            }
                        })
                        .catch(error => {
                            this.$message.error('修改失败：' + error.message)
                        })
                        .finally(() => {
                            this.submitting = false
                        })
                }
            })
        },

        // 图片上传成功处理
        handleLogoSuccess(res, file) {
            if (res.code === 200) {
                this.merchantInfo.logo = res.data.url
                this.$message.success('LOGO上传成功')
            }
        },

        handleLicenseSuccess(res, file) {
            if (res.code === 200) {
                this.merchantInfo.license = res.data.url
                this.$message.success('营业执照上传成功')
            }
        }

    },
    created() {
        this.searchMerchantInfo();
    }

}
</script>

<style scoped>
/* 图片容器 */
.image-container {
    position: relative;
    overflow: hidden;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    background: linear-gradient(135deg, #f8f9fa 25%, #ffffff 100%);
    border: 1px solid #ebeef5;
}

.image-container:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

/* LOGO样式 */
.logo-wrapper {
    width: 200px;
    height: 200px;
    margin: 0 auto;
}

.logo-image {
    width: 100%;
    height: 100%;
    background-color: #ffffff;
    padding: 10px;
    border-radius: 50%;
}

/* 营业执照样式 */
.license-wrapper {
    width: 100%;
    height: 300px;
    background: repeating-linear-gradient(
        45deg,
        #f8f9fa,
        #f8f9fa 10px,
        #ffffff 10px,
        #ffffff 20px
    );
}

.license-image {
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.9);
}

/* 悬停提示文字 */
.image-hover-text {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 8px;
    background: rgba(0, 0, 0, 0.6);
    color: white;
    text-align: center;
    font-size: 12px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.image-container:hover .image-hover-text {
    opacity: 1;
}

/* 标题美化 */
.preview-title {
    font-size: 15px;
    color: #606266;
    margin-bottom: 15px;
    font-weight: 600;
    letter-spacing: 1px;
    padding-left: 8px;
    border-left: 4px solid #409EFF;
}
/* 地址盒子样式 */
.address-box {
    display: flex;
    align-items: flex-start;
    padding: 16px;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #eaeef5;
}

.location-icon {
    font-size: 22px;
    color: #409EFF;
    margin-right: 16px;
    margin-top: 2px;
}

.address-content {
    flex: 1;
}

.address-line {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    line-height: 1.5;
}

.address-line:last-child {
    margin-bottom: 0;
}

.address-tag {
    display: inline-block;
    min-width: 60px;
    padding: 2px 8px;
    background: #ecf5ff;
    color: #409EFF;
    border-radius: 4px;
    font-size: 12px;
    text-align: center;
    margin-right: 12px;
}

.address-text {
    color: #606266;
    font-size: 14px;
}

.no-address {
    color: #909399;
    font-size: 14px;
    font-style: italic;
}
.merchant-container {
    max-width: 1200px;
    margin: 24px auto;
    padding: 0 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
}

.title {
    font-size: 20px;
    color: #303133;
}

.section {
    margin-bottom: 32px;
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.section-title {
    font-size: 16px;
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
}

/* 信息展示样式 */
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.info-item label {
    color: #909399;
    min-width: 80px;
    margin-right: 12px;
}

.address-box {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
}

.location-icon {
    font-size: 24px;
    color: #409eff;
    margin-right: 16px;
}


/* 证照展示 */
.license-grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 24px;
}

.preview-title {
    color: #909399;
    margin-bottom: 12px;
}

.preview-image {
    width: 100%;
    height: 200px;
    border: 1px solid #ebeef5;
    border-radius: 12px;
    background: #f8f9fa;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

.preview-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 16px rgba(0,0,0,0.2);
}
/* 新增样式 */
.avatar-uploader, .license-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader {
    width: 150px;
    height: 150px;
}

.license-uploader {
    width: 300px;
    height: 200px;
}

.avatar-uploader:hover, .license-uploader:hover {
    border-color: #409EFF;
}

.avatar {
    width: 100%;
    height: 100%;
    display: block;
}

.license {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
}

.uploader-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #8c939d;
}

.uploader-placeholder i {
    font-size: 40px;
    margin-bottom: 10px;
}
</style>